﻿using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Input;

using CommonLib;

namespace WordStat.Tasks
{
    public partial class TasksWindow : Window
    {
        private TaskService _taskService;
        private readonly IPlugin _plugin;

        internal TasksWindow(TaskService taskService, IPlugin plugin = null)
        {
            InitializeComponent();

            _taskService = taskService;
            _plugin = plugin;

            _dataGrid.DataContext = _taskService.TaskList;
        }

        private void _closeBtn_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void _retrieveTasksBtn_Click(object sender, RoutedEventArgs e)
        {
            var articleCountWindow = new ArticleCountWindow();

            articleCountWindow.SetData(new ArticleNumber { Number = 1 });

            var curNumber = articleCountWindow.GetNumber();

            articleCountWindow.ShowDialog();

            if (curNumber.Number == 0)
                return;

            var curCursor = Cursor;

            try
            {
                var res = _plugin.GetArticles(curNumber.Number);

                _dataGrid.ItemsSource = res.Select(x => new UrlArticle { Url = x }).ToList();
            }
            finally
            {
                Cursor = curCursor;
            }
        }

        private void _startAnalyzingBtn_Click(object sender, RoutedEventArgs e)
        {
            if (_plugin == null)
                return;

            var articleCountWindow = new ArticleCountWindow();

            articleCountWindow.SetData(new ArticleNumber { Number = 1 });

            articleCountWindow.ShowDialog();

            var curNumber = articleCountWindow.GetNumber();

            if (curNumber.Number == 0)
                return;

            var curCursor = Cursor;

            try
            {
                Cursor = Cursors.Wait;

                int r = 0;

                int index = -1;

                foreach (var iter in _dataGrid.Items)
                {
                    index++;

                    Thread.Sleep(500);

                    var url = iter as UrlArticle;
                    if (url == null)
                        continue;

                    var article = _plugin.GetArticleData(url.Url);

                    if (article == null)
                        continue;

                    TextFileService.AddInternetToDb(article);

                    r++;

                    if (r == curNumber.Number)
                        break;
                }
            }
            finally
            {
                Cursor = curCursor;
            }
        }
    }

    internal sealed class UrlArticle
    {
        public string Url { get; set; }
    }
}
